package com.mo.demo.ehcache;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.spi.serialization.Serializer;
import org.ehcache.spi.serialization.SerializerException;

import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;


@Slf4j
public class EhcacheSerializer<T> implements Serializer<T>, Closeable {


    public EhcacheSerializer() {
    }

   public Class<EhcacheSerializer<T>> getItsClass(){
        return (Class<EhcacheSerializer<T>>)this.getClass();
   }

    public EhcacheSerializer(ClassLoader classLoader) {
    }

    public static final ObjectMapper jsonMapper = new ObjectMapper(){{
        disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
    }};

    @Override
    public void close() throws IOException {
        log.debug("close...");
    }

    @Override
    public ByteBuffer serialize(T t) throws SerializerException {
        try {
            return ByteBuffer.wrap(jsonMapper.writeValueAsBytes(t));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public T read(ByteBuffer byteBuffer) throws ClassNotFoundException, SerializerException {
        try {
            return jsonMapper.readValue(byteBuffer.array(), new TypeReference<T>() {});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean equals(T t, ByteBuffer byteBuffer) throws ClassNotFoundException, SerializerException {
        return true;
    }
}
